const path = require('path');
const fs = require("fs");
const cProcess = require("child_process");
const Tools = require("./tools.js");

function trim(str){return str.replace(/^\*/, "").trim();}
function getLastOfPath(path){return path.split(/[\\/]+/).pop();}
function isThisUrlOfTheRepertory(url, repertory) {return new RegExp(`\\/${repertory}\\.git`).test(url)}

module.exports = function (req, res) {
  const cwd = process.cwd();
  const tools = Tools(req.ctoolsOpt.devToolsDir);
  let {repertory, workspace, branchs, branch, oriBranch} = req.query;
  branchs = (branchs && branchs.map(branch => trim(getLastOfPath(branch)))) || [];
  branch && branchs.push(trim(getLastOfPath(branch)));

  const confPath = path.join(cwd, "./ctools.conf/bizConfs", `${workspace}/conf.js`);
  const conf = tools.getWorkspaceConf(workspace)[0];
  let nextBranch = [];
  try {
    const repertoryPath = path.join(cwd, conf.dto.repertoryPath, repertory);
    console.log(repertoryPath);
    process.chdir(repertoryPath);
    branchs.forEach(branch => {
      const repertoryItem = conf.dto.repertoryList.find(item => isThisUrlOfTheRepertory(item.repertory, repertory));
      cProcess.execSync("git fetch");
      const allBranches = cProcess.execSync("git branch -a", {encoding: "utf-8"});
      const parsedBranch = tools.parseBranch(allBranches);

      // 检出分事不是当前分支时，才需要检出分支
      if (parsedBranch.current !== branch) {
        // 检出 要检出的源分支 // 如果源分支不存在 或者 已有分支不包含源分支， 并且要检出的分支也不再， 那么就返回
        // 如果
        if (
          // 没有源分支的话， 只能处理已有分支的情况 // 即 新分支，必须要设置源分支
          !oriBranch && !parsedBranch.remote.includes(branch) && !parsedBranch.local.includes(branch) ||
          // 有源分支， 要保证源分支存在
          !(parsedBranch.remote.includes(oriBranch) || parsedBranch.local.includes(oriBranch))
        ) return;
        cProcess.execSync(`git checkout ${oriBranch}`, {encoding: "utf-8"});

        // 是否已有分支 // 如果没有就新建一个分支
        if (!parsedBranch.remote.includes(branch) && !parsedBranch.local.includes(branch)) {
          cProcess.execSync(`git branch ${branch}`);
        }
        // 然后检出分支 // 新建的也检出一下；
        cProcess.execSync(`git checkout ${branch}`, {encoding: "utf-8"});

        // 关联远程分支
        if (!parsedBranch.remote.includes(branch)) {
          cProcess.execSync(`git push origin ${branch}`, {encoding: "utf-8"});
        }
      } else {}
      let next = tools.parseBranch(cProcess.execSync("git branch -a", {encoding: "utf-8"})).current;
      nextBranch.push(repertoryItem);
      repertoryItem.branch = next;
      fs.writeFileSync(confPath, `module.exports = ${JSON.stringify(conf.dto)}`);
    });
    res.send({data: nextBranch, code: 0});
    process.chdir(cwd);
  } catch (e) {
    console.log(e);
    process.chdir(cwd);
    res.send({data: null, code: 0});
  }
};
